//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.client.setting;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import tv.dyndns.kishibe.client.Service;
import tv.dyndns.kishibe.client.UserData;
import tv.dyndns.kishibe.client.game.ProblemGenre;
import tv.dyndns.kishibe.client.game.ProblemType;
import tv.dyndns.kishibe.client.packet.PacketTheme;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class PanelSettingThemeMode extends VerticalPanel implements ClickHandler {
	private static final String DESCRIPTION = createDescription();
	private static final Logger logger = Logger.getLogger(PanelSettingThemeMode.class.getName());
	private static final int PLAY_COUNT_THRESHOLD = 100;
	private static final int MAX_THEME_LENGTH = 8;
	private static final int MAX_QUERY_LENGTH = 32;
	private static final int UPDATE_PERIOD = 1000;
	private final Grid grid = new Grid();
	private final TextBox textBoxTheme = new TextBox();
	private final TextBox textBoxQuery = new TextBox();
	private final Button buttonAdd = new Button("追加", this);
	private final Button buttonRemove = new Button("削除", this);
	private final Button buttonApplication = new Button("テーマモードの編集権限の申請をする(確認画面が出ます)", this);
	private final TextBox textBox = new TextBox();
	private final RepeatingCommand commandUpdateForm = new RepeatingCommand() {
		@Override
		public boolean execute() {
			updateForm();
			return isAttached();
		}
	};

	public PanelSettingThemeMode() {
		Service.Util.getInstance().isThemeModeEditor(UserData.get().getUserCode(),
				callbackIsThemeModeEditor);
	}

	private final AsyncCallback<Boolean> callbackIsThemeModeEditor = new AsyncCallback<Boolean>() {
		public void onSuccess(Boolean result) {
			if (result) {
				displayEditForm();
			} else if (UserData.get().getPlayCount() >= PLAY_COUNT_THRESHOLD) {
				displayHaveRight();
			} else {
				displayNoRight();
			}
		}

		public void onFailure(Throwable caught) {
			logger.log(Level.WARNING, "テーマモード編集権限の取得に失敗しました", caught);
		}
	};

	private void displayEditForm() {
		add(new HTML(new SafeHtmlBuilder().appendEscapedLines(DESCRIPTION).toSafeHtml()));

		grid.addStyleName("gridFrame");
		final ScrollPanel scrollPanel = new ScrollPanel();
		scrollPanel.setPixelSize(600, 480);
		scrollPanel.setWidget(grid);
		add(scrollPanel);

		{
			final HorizontalPanel panel = new HorizontalPanel();
			textBoxTheme.setWidth("200px");
			textBoxTheme.setMaxLength(MAX_THEME_LENGTH);
			textBoxQuery.setWidth("200px");
			textBoxQuery.setMaxLength(MAX_QUERY_LENGTH);
			panel.add(new HTML("テーマ"));
			panel.add(textBoxTheme);
			panel.add(new HTML("単語"));
			panel.add(textBoxQuery);
			panel.add(buttonAdd);
			panel.add(buttonRemove);
			add(panel);
		}

		loadThemes();
	}

	private void displayNoRight() {
		add(new HTML(
				"100回以上プレイされた方はテーマモードの編集が出来ます。<br>編集権限を御希望の方は100回以上プレイされた後、<br>この画面から申請してください。"));
	}

	private void displayHaveRight() {
		add(new HTML("テーマモードの編集権限の申請が出来ます。<br>編集権限を御希望の方は以下のボタンを押してください。"));

		Service.Util.getInstance().isApplyingThemeModeEditor(UserData.get().getUserCode(),
				callbackIsApplyingThemeModeEditor);
	}

	private final AsyncCallback<Boolean> callbackIsApplyingThemeModeEditor = new AsyncCallback<Boolean>() {
		public void onSuccess(Boolean result) {
			if (result) {
				add(buttonApplication);
				buttonApplication.setText("現在申請中です。承認されるまでしばらくお待ちください。");
				buttonApplication.setEnabled(false);
			} else {
				add(new HTML("申請にあたり作りたい検定や自己アピール等をお願いいたします。"));
				textBox.setWidth("400px");
				add(textBox);
				add(buttonApplication);
			}
		}

		public void onFailure(Throwable caught) {
			logger.log(Level.WARNING, "テーマモード編集権限の申請に失敗しました", caught);
		}
	};

	private void loadThemes() {
		Service.Util.getInstance().getThemes(callbackGetThemeModeQuery);
	}

	private final AsyncCallback<List<PacketTheme>> callbackGetThemeModeQuery = new AsyncCallback<List<PacketTheme>>() {
		public void onSuccess(List<PacketTheme> result) {
			setGrid(result);
		}

		public void onFailure(Throwable caught) {
			logger.log(Level.WARNING, "テーマモードクエリ一覧の取得に失敗しました", caught);
		}
	};

	public interface MyTemplate extends SafeHtmlTemplates {
		@Template("{0} ({1})")
		SafeHtml theme(String name, int numberOfProblems);
	}

	private static final MyTemplate TEMPLATE = GWT.create(MyTemplate.class);

	private void setGrid(List<PacketTheme> themes) {
		grid.resize(themes.size() + 1, 2);
		grid.setHTML(0, 0, "テーマ");
		grid.setHTML(0, 1, "単語");

		int row = 1;
		for (PacketTheme theme : themes) {
			final String name = theme.name;
			grid.setHTML(row, 0, TEMPLATE.theme(name, theme.numberOfProblems));

			final FlowPanel flowPanel = new FlowPanel();
			for (final String query : theme.queries) {
				final Button button = new Button(SafeHtmlUtils.fromString(query),
						new ClickHandler() {
							public void onClick(ClickEvent event) {
								textBoxTheme.setText(name);
								textBoxQuery.setText(query);
							}
						});
				flowPanel.add(button);
				flowPanel.setWidth("400px");
			}
			grid.setWidget(row, 1, flowPanel);
			++row;
		}
	}

	public void onClick(ClickEvent event) {
		final Object source = event.getSource();
		if (source == buttonAdd) {
			final String theme = textBoxTheme.getText();
			final String query = textBoxQuery.getText();
			Service.Util
					.getInstance()
					.addThemeModeQuery(theme, query, callbackUpdateThemeModeQuery);

		} else if (source == buttonRemove) {
			final String theme = textBoxTheme.getText();
			final String query = textBoxQuery.getText();
			Service.Util.getInstance().removeThemeModeQuery(theme, query,
					callbackUpdateThemeModeQuery);

		} else if (source == buttonApplication) {
			if (Window.confirm("テーマモードの編集権限の申請をします\nよろしいですか？")) {
				Service.Util.getInstance().applyThemeModeEditor(UserData.get().getUserCode(),
						textBox.getText(), callbackApplyThemeModeEditor);
				buttonApplication.setText("現在申請中です。承認されるまでしばらくお待ちください。");
				buttonApplication.setEnabled(false);
			}
		}
	}

	private final AsyncCallback<Void> callbackApplyThemeModeEditor = new AsyncCallback<Void>() {
		@Override
		public void onSuccess(Void result) {
		}

		@Override
		public void onFailure(Throwable caught) {
			logger.log(Level.WARNING, "テーマモードの申請に失敗しました", caught);
		}
	};

	private final AsyncCallback<Void> callbackUpdateThemeModeQuery = new AsyncCallback<Void>() {
		public void onSuccess(Void result) {
			loadThemes();
		}

		public void onFailure(Throwable caught) {
			logger.log(Level.WARNING, "テーマモードクエリの更新に失敗しました", caught);
		}
	};

	private void updateForm() {
		final boolean enabled = checkForm();
		buttonAdd.setEnabled(enabled);
		buttonRemove.setEnabled(enabled);
	}

	private boolean checkForm() {
		return textBoxTheme.getText().length() > 0 && textBoxQuery.getText().length() > 0;
	}

	@Override
	protected void onLoad() {
		super.onLoad();
		Scheduler.get().scheduleFixedDelay(commandUpdateForm, UPDATE_PERIOD);
	}

	private static String createDescription() {
		StringBuilder sb = new StringBuilder();
		sb.append("申請有難うございました。\n");
		sb.append("\n");
		sb.append("テーマモードのテーマの設定を行います。\n");
		sb.append("それぞれのテーマは「テーマ」と「単語」の組み合わせでできています。\n");
		sb.append("それぞれのテーマに設定されている単語が文章中に含まれる問題が出題されます。\n");
		sb.append("問題検索同様「-」による除外検索を行うこともできます\n");
		sb.append("テーマの後の()内の数字は条件に合致した問題数です\n");
		sb.append("ロビーには100問以上登録されている問題のみ表示されます\n");
		sb.append("\n");
		sb.append("「ジャンル:」から始まる単語を指定すると特定のジャンルで絞り込むことができます。使用できる単語は以下の通りです。\n");
		for (ProblemGenre genre : ProblemGenre.values()) {
			sb.append("「ジャンル:").append(genre.toString()).append("」");
		}
		sb.append("\n");
		sb.append("\n");
		sb.append("「問題形式:」から始まる単語を指定すると特定の問題形式で絞り込むことができます。使用できる単語は以下のとおりです。\n");
		for (ProblemType type : ProblemType.valuesWithoutRandom) {
			sb.append("「問題形式:").append(type.toString()).append("」");
		}
		sb.append("\n");
		sb.append("\n");
		sb.append("「問題作成者:」から始まる単語を指定すると特定の問題作成者で絞り込むことができます。(例:「問題作成者:ノドチップ」\n");
		return sb.toString();
	}
}
